<?php
	session_start();

	$response;
	$userId;

	changeEmail();

	function changeEmail(){
		global $response, $userId;

		$userName = $_SESSION['userName'];
		$oldEmail = $_GET['oldEmail'];
		$newEmail = $_GET['newEmail'];

		$response = array (
			'success' => false
		);

		$userExists = false;
		
		$userFile = fopen('../userInfo/users.txt', 'r') or die("can't open the user info file");
		while(($buffer = fgets($userFile)) != false){
			$user = explode(",", $buffer);
			if($userName == $user[0]){
				$userId = trim($user[1]);
				$userExists = true;
				break;
			}
		}
		fclose($userFile);

		if(updateEmail($oldEmail, $newEmail)) {
			$response['success'] = true;
		}

		echo json_encode($response);
	}

	function updateEmail($oldEmail, $newEmail){
		global $response, $userId;

		$userEmails = file("../userInfo/email.txt", FILE_SKIP_EMPTY_LINES);
		foreach($userEmails as $line_num => $user){
			$user = explode(',', $user);
			if(trim($user[1]) === $userId && trim($oldEmail) === trim($user[0])){
				$user[0] = $newEmail;
				$user = implode($user,',');
				$userEmails[$line_num] = $user;
				$userEmails = implode($userEmails);
				updateEmailFile($userEmails);
				return true;
			}
		}

		return false;
	}

	function updateEmailFile($userEmailString){
		$userEmailsFile = fopen("../userInfo/email.txt", 'w+') or die("can't oper user infor file");
		fwrite($userEmailsFile, $userEmailString);
		fclose($userEmailsFile);
	}
?>